<template>
  <div>
    <el-form
      :model="roleData"
      ref="form"
      label-width="80px"
      :inline="false"
      size="default"
    >
      <el-form-item label="角色名称">
        <el-input v-model="roleData.name"></el-input>
      </el-form-item>
      <el-form-item label="角色权限">
        <el-tree
          ref="treeRef"
          :data="routes[0].children"
          show-checkbox
          default-expand-all
          node-key="path"
          highlight-current
          :props="{
            label: (data) => {
              //   console.log(data);
              return data.meta.title;
            },
          }"
          @check="handleCheck"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="onSubmit" v-if="edata"
          >确认修改</el-button
        >
        <el-button type="primary" @click="onSubmit" v-else>立即新增</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElTree } from "element-plus";
import type Node from "element-plus/es/components/tree/src/model/node";
import { routes } from "../../../router/index";
import { RoleType } from "../../../types/user";
import { rolePost, rolePut } from "../../../api/user";
const emit = defineEmits();
const roleData: Omit<RoleType, "objectId"> = reactive({
  name: "",
  permission: [],
});
const onSubmit = () => {
  if (props.edata) {
    //修改
    let { objectId } = props.edata;
    rolePut(objectId, roleData).then((res) => {
      emit("update:table-data", {
        ...roleData,
        objectId,
      });
    });
  } else {
    // 新增
    rolePost(roleData).then((res) => {
      emit("update:table-data", {
        ...roleData,
        objectId: res.data.objectId,
      });
    });
  }
};

// 树组件
interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}

const treeRef = ref<InstanceType<typeof ElTree>>();
const handleCheck = (
  _: any,
  { checkedKeys }: { checkedKeys: Array<string> }
) => {
  console.log(checkedKeys);
  roleData.permission = checkedKeys;
};

// 区分新增、编辑
// props数据具备单向性
type PropsType = {
  edata: RoleType | null;
};
const props = defineProps<PropsType>();
console.log("接收到了父级的props", props.edata);
onMounted(() => {
  if (props.edata) {
    //编辑
    let { name, permission } = props.edata;
    roleData.name = name;
    roleData.permission = permission;
    treeRef.value?.setCheckedKeys(permission); //设置tree组件默认勾选的元素
  } else {
    // 新增
    roleData.name = "";
    roleData.permission = [];
  }
});
</script>

<style scoped></style>
